#!/usr/bin/env python
# -*- coding: utf-8 -*



import logging
log = logging.getLogger("application")

import store
import templates
from base import RTorrent
from util import partial



class RTorrentApplication:
    """ REST 'Storage' WSGI Application """
    def __init__(self, environ, start_response):
        self.environ = environ
        self.start_response = start_response
        self.dispatch()

    def start(self, status, response_headers):
        log.debug("Status of request %s %s : %s", self.method, self.path, status)
        self.start_response(status, response_headers)

    def dispatch(self):
        """ Dispatches url to function

        Sets self.__iter__ to desired function
        """

        self.method = self.environ['REQUEST_METHOD']
        self.client_ip = self.environ.get('REMOTE_ADDR', 'uknown')
        self.path = self.environ['PATH_INFO'] or self.environ['REQUEST_URI']

        log.debug("%s calls: %s %s", self.client_ip, self.method, self.path)

        if self.method == 'GET':
            if self.path in ('/', '/index', '/index.html'):
                self.__iter__ = partial(self.index)
            elif self.path in ('/info'):
                self.__iter__ = partial(self.info)
            elif self.path.startswith('/torrent'):
                torrent_id = self.path.split('/')[-1]
                self.__iter__ = partial(self.torrent_detail, torrent_id)
            else:
                self.__iter__ = partial(self.status, '404 Not Found', 'Not Found')


    def index(self):
        # context
        torrents = store.rtorrent.torrents.items()[:5]
        torrents.sort(key = lambda x : x[1].name) #RTorrent.get_cmp())
        # render
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        response_html = templates.index_template.render(torrents = torrents)

        self.start(status, response_headers)

        yield response_html

    def torrent_detail(self, torrent_id):
        # context
        torrent = store.rtorrent.torrents[torrent_id]
        # render
        status = '200 OK'
        response_headers = [('Content-type','text/html')]
        response_html = templates.torrent_detail_template.render(torrent = torrent)

        self.start(status, response_headers)

        yield response_html

    def info(self):
        # context
        methods = store.rtorrent.methods
        # render
        status = '200 OK'
        response_headers = [('Content-type','text/html')]

        response_html = templates.info_template.render(methods = methods)

        self.start(status, response_headers)

        yield response_html

    def status(self, status_code, text):
        self.start(status_code,  [('Content-type','text/html')])
        yield text



if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG, format='%(levelname)s %(message)s')

    rt = RTorrentApplication()

